package Thread;

import Mysql.Database;
import Mysql.ShareData;
import instruction.*;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.sql.SQLException;
import java.util.*;

public class ServerInstructionJudge implements Runnable {
    private static Map<String, ObjectOutputStream> loginMap = new HashMap<>();
    private static Map<String, UserData> userMap = new HashMap<>();
    private ObjectInputStream ois = null;
    private ObjectOutputStream oos = null;

    public ServerInstructionJudge(Socket socket) throws IOException {
        ois = new ObjectInputStream(socket.getInputStream());
        oos = new ObjectOutputStream(socket.getOutputStream());
    }

    //根据对象的不同，处理不同的指令,开不同的线程
    @Override
    public void run() {
        boolean isRunning = true;
        try {
            while (isRunning) {
                Message message=(Message)ois.readObject();
                String type=message.getMessageType();
                if (type.equals("login")) {//登录指令
                    if (Database.login(message.getLogin())) {
                        String user_account = message.getLogin().getAccount();
                        System.out.println("账号：" + user_account + "已上线");
                        loginMap.put(user_account, oos);//存储已经上线的用户
                        User user = Database.GetUser(user_account);//获取用户信息
                        ArrayList<Friend> friendList = Database.GetAllFriend(user_account);//所有好友
                        ArrayList<Group> groupList = Database.GetAllGroup(user_account);//所有群聊
                        ArrayList<ArrayList<Message>> groupRecord=Database.GetGroupRecord(groupList);//获取群聊消息记录
                        ArrayList<ArrayList<Message>> friendRecord=Database.GetPrivateRecord(friendList);//获取私聊记录
                        UserData userData = new UserData(user_account, user, friendList, groupList,groupRecord,friendRecord);
                        Message message1=new Message("userData");
                        message1.setUserData(userData);
                        oos.writeObject(message1);//返回全部信息
                        oos.flush();
                    }
                } else if (type.equals("register")) {//注册指令
                    Database.register(message.getRegister());
                } else if (type.equals("forget")) {//忘记密码指令
                    Database.forget(message.getForget());
                } else if (type.equals("search")) {//搜索
                    if(message.getSearch().getSignal().equals("1")) {//加好友，获取好友的全部信息
                        Message message1=new Message("User");
                        message1.setUser(Database.GetUser(message.getSearch().getAccount()));
                            oos.writeObject(message1);
                            oos.flush();
                    }else if(message.getSearch().getSignal().equals("2")) {//加群，获取群的全部信息
                        Message message1 = new Message("group");
                        message1.setGroup(Database.GetGroup(message.getSearch().getAccount()));
                        oos.writeObject(message1);
                        oos.flush();
                    }
                } else if (type.equals("addFriend")) {//添加好友
                    Database.AddFriend(message.getFriend());
                    for (Map.Entry<String, ObjectOutputStream> entry : loginMap.entrySet()) {
                        if (message.getFriend().getUserAccount().equals(entry.getKey())) {
                            entry.getValue().writeObject(message);
                            entry.getValue().flush();
                            break;
                        }
                    }
                }else if(type.equals("addGroup")){
                    Database.AddGroup(message.getGroupMember());
                    for (Map.Entry<String, ObjectOutputStream> entry : loginMap.entrySet()) {
                        if (message.getGroupMember().getMember().getAccount().equals(entry.getKey())) {
                            entry.getValue().writeObject(message);
                            entry.getValue().flush();
                            break;
                        }
                    }
                } else if (type.equals("privateChat")) {//私聊消息
                    PrivateMessage privateMessage =message.getPrivateMessage();
                    String type1=privateMessage.getType();
                    String sender=privateMessage.getSendAccount();
                    String receiver=privateMessage.getReceiveAccount();
                    String content=privateMessage.getContent();
                    String time=privateMessage.getTime();
                        if(type1.equals("word")||type1.equals("emoticon")) {
                            Record record= new Record(type1, sender, receiver, content, time);;
                        Database.Record(record);//存储消息记录
                    }else if(type1.equals("picture")){
                            Record record= new Record(type1, sender, receiver, content, time);;
                        record.setPicture(privateMessage.getPicture());
                        Database.Record(record);
                    }
                    for (Map.Entry<String, ObjectOutputStream> entry : loginMap.entrySet()) {
                        if (message.getPrivateMessage().getReceiveAccount().equals(entry.getKey())) {
                            entry.getValue().writeObject(message);
                            entry.getValue().flush();
                            break;
                        }
                    }
                } else if (type.equals("createGroup")) {//创建群聊
                    Database.createGroup(message.getCreateGroup());
                    for (Map.Entry<String, ObjectOutputStream> entry : loginMap.entrySet()) {
                        if (message.getCreateGroup().getCreator().equals(entry.getKey())) {
                            entry.getValue().writeObject(message);
                            entry.getValue().flush();
                            break;
                        }
                    }
                } else if (type.equals("groupChat")) {
                    GroupMessage groupMessage =message.getGroupMessage();
                    String sender=groupMessage.getSender();
                    String receiver=groupMessage.getReceiver();
                    String content=groupMessage.getContent();
                    String time=groupMessage.getTime();
                    String type1=groupMessage.getType();
                    Record record = new Record(type1, sender, receiver, content, time);
                    if(type1.equals("word")||type1.equals("emoticon")) {
                        Database.Record(record);
                    }else if(type1.equals("picture")){
                        record.setPicture(groupMessage.getPicture());
                        Database.Record(record);
                    }
                   Database.GetGroupMember(groupMessage.getReceiver());
                   ArrayList<Member> memberList=Database.GetGroupMember(groupMessage.getReceiver());
                    for (int i = 0; i < memberList.size(); i++) {
                        if(loginMap.get(memberList.get(i).getAccount())!=null){
                            loginMap.get(memberList.get(i).getAccount()).writeObject(message);
                            loginMap.get(memberList.get(i).getAccount()).flush();
                        }
                    }
                }else if(type.equals("modify"))
                {
                      Database.modify(message.getModify());
                }
                else {
                    System.out.println("该功能尚未实现");
                }
            }
        } catch (IOException | SQLException | ClassNotFoundException e) {
            e.printStackTrace();
            isRunning = false;
        }
    }
}
